package org.jinghouyu.caculator.engine;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class TextScanner {
	
	private static Set<Character> spaces = new HashSet<>(Arrays.asList(new Character[]{' ', '\n', '\r', '\t'}));
	
	private String text;
	
	private int pos = -1;
	
	
	public TextScanner(String text) { //分析一次，将-号调优
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < text.length(); i++) {
			if(!spaces.contains(text.charAt(i))) {
				sb.append(text.charAt(i));
			}
		}
		this.text = sb.toString();
	}
	
	private static final Set<Character> symbols = new HashSet<>(Arrays.asList(new Character[]{'+','-','*','/'}));
	
	public String nextWord() { //没有括号
		int kuoCount = 0;
		StringBuilder sb = new StringBuilder();
		boolean nonValidKuo = false;
		while(true) {
			Character c = next();
			if(c == null) break;
			if(c == '(') {
				if(kuoCount == 0) {
					if(!isValidKuo()) {
						nonValidKuo = true;
						sb.append(c);
					} else {
						if(!sb.toString().trim().equals("")) {
							pos--;
							return sb.toString();
						}
					}
				} else {
					sb.append(c);
				}
				kuoCount++;
			} else if(c == ')') {
				kuoCount--;
				if(nonValidKuo || kuoCount != 0) {
					sb.append(c);
				}
				if(nonValidKuo && kuoCount == 0) {
					nonValidKuo = false;
				}
			} else {
				sb.append(c);
			}
			if(symbols.contains(c) && kuoCount == 0) {
				if(c == '-') {
					if(pos - 1 >= 0) {
						char pre = text.charAt(pos - 1);
						if(pre != '(') {
							String s = sb.substring(0, sb.length() - 1);
							if(s.equals("")) {
								return c + "";
							} else {
								pos--;
								return s;
							}
						}
					}
				} else {
					String s = sb.substring(0, sb.length() - 1);
					if(s.equals("")) {
						return c + "";
					} else {
						pos--;
						return s;
					}
				}
			}
		}
		if(sb.toString().trim().equals("")) return null;
		return sb.toString();
	}
	
	private boolean isValidKuo() {
		int pos = this.pos - 1;
		if(pos < 0) return true;
		char c = text.charAt(pos);
		return symbols.contains(c);
	}
	
	public static void main(String[] args) {
		TextScanner scanner = new TextScanner("-123+2-3+4+5+(1-2)+math(5+(-1+1))+ceil(123)+random(1, 1+2)");
		while(true) {
			String w = scanner.nextWord();
			if(w == null) break;
			System.out.println(w);
		}
	}
	
	private Character next() {
		skipWhiteSpaces();
		return _next();
	}
	
	private Character _next() {
		int pos = this.pos + 1;
		if(pos >= text.length()) {
			return null;
		}
		this.pos = pos;
		return text.charAt(pos);
	}
	
	private void skipWhiteSpaces() {
		Character next = _next();
		if(next != null) {
			if(!spaces.contains(next)) {
				pos = pos - 1;
			} 
		}
	}
	
	public int getPos() {
		return this.pos;
	}
	
	public String getText() {
		return this.text;
	}
}